<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020-8-11
 * Time: 18:07
 */

namespace App\Handlers;

use App\Models\Deposite;
use App\Models\UserBalanceLog;
use App\Models\Withdrawal;
use App\Models\AdminUser;
use App\Models\CommissionLog;


class WithdrawalHandler
{

    protected $deposite;


    public function __construct()
    {

    }

    /***
     * 审核不通过，退款给用户
     * @param $withdrawal 退款数据
     */
    public static function refundUserMoney($withdrawal, $remarks = '...')
    {
        $form = $withdrawal;
        $user = $withdrawal->admin_user;

        // 金额流水表
        $UserBalanceLog              = new UserBalanceLog();
        $UserBalanceLog->amount_type = $form->amount_type;//需处理类型
        $UserBalanceLog->user_id     = $user->id;// 用户ID
        $UserBalanceLog->now_amount  = $form->usd_amount; //需处理余额

        switch ($form->amount_type) {
            case 1:
                $UserBalanceLog->before_amount = $user->trade_balance;//处理前余额
                $user->trade_balance           += $form->usd_amount;
                $UserBalanceLog->after_amount  = $user->trade_balance;//处理后余额
                break;
            case 2:
                $UserBalanceLog->before_amount = $user->agent_balance;//处理前余额
                $user->agent_balance           += $form->usd_amount;
                $UserBalanceLog->type          = 3;//佣金投出审核不通过退回 3
                $UserBalanceLog->after_amount  = $user->agent_balance;//处理后余额
                break;
            case 3:
                $UserBalanceLog->before_amount = $user->investment_amount;//处理前投入数量
                $user->investment_amount       += $form->usd_amount;
                $UserBalanceLog->after_amount  = $user->investment_amount;//处理投入数量
                break;
        }
        $UserBalanceLog->remarks = $remarks;
        if ($UserBalanceLog->save() && $user->save()) {
            recordUserLog($remarks);
        }
    }


    /***
     * 用户 出产品数量流水表日志
     * @param          $data  传入数量
     * @param  string  $type  投入还是投出 1 投入
     * @return bool
     */
    public static function inToOutLogMoney($data, $type = '1')
    {
        // 金额流水表
        $UserBalanceLog              = new UserBalanceLog();
        $UserBalanceLog->user_id     = $data['id'];   // 用户ID
        $UserBalanceLog->amount_type = 3; // 投入类型
        $UserBalanceLog->remarks     = $data['notes'];// 备注
        $UserBalanceLog->created_at  = $data['created_at'] ?? date('Y-m-d H:i:s');

        $UserBalanceLog->before_amount = $data['investment_amount'] ?? 0; // 当前余额
        if ($type == 1) {
            $UserBalanceLog->now_amount   = $data['amount'];  // 要处理的余额
            $UserBalanceLog->after_amount = $UserBalanceLog->before_amount + $data['amount']; //处理后的余额
        } elseif ($type == 2) {
            $UserBalanceLog->now_amount   = -$data['amount'];  // 要处理的余额
            $UserBalanceLog->after_amount = $UserBalanceLog->before_amount - $data['amount']; //处理后的余额
        }
        return $UserBalanceLog->save();
    }


    /***
     * 客户投出投入 处理方法
     * @param $data 数据
     * @return bool
     */
    public static function inToOutDeposite($data)
    {
        $rate = \Config::get('app.rate');
        if ($data['amount_type'] == 1) { // 产品投入
            $deposite             = new Deposite();
            $deposite->user_id    = $data['id'];
            $deposite->admin_id   = $data['admin_id'];
            $deposite->usd_amount = $data['amount'];
            $deposite->notes      = $data['notes'];
            $deposite->type       = $data['type'];
            $deposite->created_at = $data['created_at'] ?? date('Y-m-d H:i:s');
            if ($deposite->save()) {
                recordUserLog('产品投入:'.$data['notes']);
                return true;
            }
        } else {
            if ($data['amount_type'] == 2) { // 产品投出
                $user       = AdminUser::where('id', $data['id'])->first();
                $withdrawal = new Withdrawal();

                $withdrawal->del_amount          = 0;
                $withdrawal->rmb_del_amount      = 0;
                $withdrawal->usd_amount          = $data['amount'];
                $withdrawal->rmb_amount_received = $data['amount'] * $rate;
                $withdrawal->admin_id            = $data['admin_id'];
                $withdrawal->rate                = \Config::get('app.rate');
                $withdrawal->sp_status           = 0;
                $withdrawal->amount_type         = 3;
                $withdrawal->type                = 1;
                $withdrawal->user_id             = $user->id;
                $withdrawal->bank_user           = $user->name;
                $withdrawal->bank_name           = $user->bank_type;
                $withdrawal->bank_number         = $user->bank_number;
                $withdrawal->bank_address        = $user->bank_address ?? '';
                $withdrawal->notes               = $data['notes'];
                $withdrawal->created_at          = $data['created_at'] ?? date('Y-m-d H:i:s');

                if ($withdrawal->save()) {
                    recordUserLog('产品投出:'.$data['notes']);
                    return true;
                }
            }
        }
        return false;
    }


    /***
     * 审核通过
     * 给上级返佣金 10%
     * @param $withdrawal  申请投投出额对象
     * @return bool
     */
    public static function upUserCommission($withdrawal, $remarks = '...')
    {
        recordUserLog($remarks);

        if ($withdrawal->amount_type != 2) {
            return;
        }

        $form = $withdrawal; // 申请投出数据
        $user = $withdrawal->admin_user; // 用户
        $sxf  = meterUserFee($form);// 计算佣金

        // 金额流水表
        $UserBalanceLog = new UserBalanceLog();

        if ($returnUser = self::userTree($user)) {

            $UserBalanceLog->amount_type = $form->amount_type;//需处理类型
            $UserBalanceLog->user_id     = $returnUser->id;// 用户ID
            $UserBalanceLog->now_amount  = $sxf; //需处理余额

            //处理前余额
            $UserBalanceLog->before_amount = $returnUser->agent_balance;
            // 给上级返佣金 10%
            $returnUser->increment('agent_balance', $UserBalanceLog->now_amount);
            //处理后余额
            $UserBalanceLog->after_amount = $returnUser->agent_balance;
            if ($UserBalanceLog->save()) {
                $data['user_id']     = $returnUser->id; // 收益用户ID
                $data['inferior_id'] = $form->user_id; // 提现用户ID
                $data['money']       = $sxf; // 提现用户手续费
                CommissionLog::create($data);
                recordUserLog('用户金额流水发生变化');
                return true;
            }
        }
        return false;
    }


    /***
     * 给推荐人返佣金10%，
     * 上级投入数量不足3000将给上级，一直往上直到公司帐号
     * @param $user 投出用户
     * @param $sxf  手续费
     * @return mixed
     */
    public static function userTree($user)
    {

        $newUser = $user->where('id', $user->tjr_id)->first();

        //if($newUser->investment_amount < 3000 && $newUser->tjr_id != 0){
        if ($newUser->users_leader_id == 0 && $newUser->tjr_id != 0) {
            return self::userTree($newUser);
        }
        return $newUser;
    }


    /***
     * 用户金额流水记录
     * 这里相减, 条件为 负处理, 处理金额1000 - 处理前余额5000 = -5000 请在调用前处理
     * @param          $user     用户数据
     * @param  int     $symbol   加还是减 ,默认为:加
     * @param  int     $type     产品类型(1投资产品2下级产品3投入数量) 默认为:投资产品
     * @param  int     $yj_type  下级产品 类型，是周结算返佣金还是 下级提现返佣金 0为提现，1为周结算
     * @param  string  $remarks
     * @param  string profit_checkout  需处理余额必须要是user数据里面， 保存的时候在删除
     */
    public static function UserBalanceLog($user, $remarks = '...', $type = 1, $yj_type = 0, $symbol = 1)
    {
        // 金额流水表
        $UserBalanceLog              = new UserBalanceLog();
        $UserBalanceLog->remarks     = $remarks; // 备注
        $UserBalanceLog->amount_type = $type;// 需处理类型
        $UserBalanceLog->user_id     = $user->id;// 用户ID
        $UserBalanceLog->now_amount  = $symbol == 1 ? $user->profit_checkout : -$user->profit_checkout; //需处理余额 负数

        switch ($type) {
            case 1://投资产品
                $UserBalanceLog->before_amount = $user->trade_balance;//处理前余额
                if ($symbol == 1) {
                    $user->trade_balance += $user->profit_checkout;
                } else {
                    $user->trade_balance -= $user->profit_checkout;
                }
                $UserBalanceLog->after_amount = $user->trade_balance;//处理后余额
                break;
            case 2://下级产品
                $UserBalanceLog->before_amount = $user->agent_balance;//处理前余额
                if ($symbol == 1) {
                    $user->agent_balance += $user->profit_checkout;
                } else {
                    $user->agent_balance -= $user->profit_checkout;
                }
                $UserBalanceLog->type         = $yj_type;                    //下级产品 类型，是周结算返佣金还是 下级提现返佣金
                $UserBalanceLog->after_amount = $user->agent_balance;//处理后余额
                break;
            case 3://投入数量
                $UserBalanceLog->before_amount = $user->investment_amount;//处理前余额
                if ($symbol == 1) {
                    $user->investment_amount += $user->profit_checkout;
                } else {
                    $user->investment_amount -= $user->profit_checkout;
                }
                $UserBalanceLog->after_amount = $user->investment_amount;//处理后余额
                break;
        }

        unset($user->profit_checkout);
        $UserBalanceLog->save();
        return $user->save();
    }


    /***
     * 申请投出 扣除用户对应金额
     * @param $form
     * @param $user
     */
    public static function deductionUserMoney($withdrawal, $remarks = '...')
    {
        $form = $withdrawal;
        $user = $withdrawal->admin_user;

        // 金额流水表
        $UserBalanceLog              = new UserBalanceLog();
        $UserBalanceLog->amount_type = $form->amount_type;//需处理类型
        $UserBalanceLog->user_id     = $user->id;// 用户ID
        $UserBalanceLog->now_amount  = -$form->usd_amount; //需处理余额 负数

        switch ($form->amount_type) {
            case 1:
                $UserBalanceLog->before_amount = $user->trade_balance;//处理前余额
                $user->trade_balance           -= $form->usd_amount;
                $UserBalanceLog->after_amount  = $user->trade_balance;//处理后余额
                break;
            case 2:
                $UserBalanceLog->before_amount = $user->agent_balance;//处理前余额
                $user->agent_balance           -= $form->usd_amount;
                $UserBalanceLog->type          = 2;//佣金投出提现定义 2
                $UserBalanceLog->after_amount  = $user->agent_balance;//处理后余额
                break;
        }
        $UserBalanceLog->remarks = $remarks;
        $UserBalanceLog->save();
        $user->save();
        recordUserLog($remarks, '...');
    }


}
